var stringify = require('../../utils/stringify');
import cax from '/cax/index'
let gStage = null;
let gTargetCtx = null;

let gOffScreenCanvas = null;
let gOffScreenCtx = null;

let gTargetImageCount = 0;

let gTestRect = null;
let gTestImage = null;

let testDrawData = [{
        type: "rect",
        tag: "g_test_rect_0",
        posx: 0,
        posy: 0,
        width: 10,
        height: 10,
        scalex: 1,
        scaley: 1,
}, {
        type: "image",
        src: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/jd_starbucks/scale.png",
        // src: "/img/scale.png",
        tag: "g_test_iamge_0",
        posx: 100,
        posy: 100,
        width: 100,
        height: 100,
        orignWidth: 36,
        orignHeight: 36,
}, {
        type: "text",
        src: "Hello World Test Text !",
        tag: "g_test_text_0",
        posx: 50,
        posy: 100,
        fontColor: "#ff0000",
        font: "20px sans-serif"
}];

Page({
        data: {
                thisStage: null,
                canvasWidth: 0,
                canvasHeight: 0,
                pixelRatio: 0
        },

        onShow: function (options) {
                let info = jd.getSystemInfoSync()
                let _self = this;
                this.setData({
                        canvasWidth: info.windowWidth ? info.windowWidth * 0.8 : 300,
                        canvasHeight: info.windowWidth ? info.windowWidth * 0.6 : 200,
                        pixelRatio: info.pixelRatio ? info.pixelRatio : 2
                })

                console.log(`caxIndex onShow --- ${this.data.canvasWidth} --- ${this.data.canvasHeight} --- ${this.data.pixelRatio}`);
                setTimeout(() => {
                        _self.initAndDrawCax();
                }, 1000);
                // this.initAndDrawCax();
                gTargetCtx = jd.createCanvasContext('targetcanvas');
        },

        initAndDrawCax() {
                let _self = this;
                gStage = new cax.Stage(this.data.canvasWidth, this.data.canvasHeight, 'myCax', this)

                setTimeout(() => {
                        let drawRect = function (info) {
                                let testRect = new cax.Rect(info.width, info.height, {
                                        lineWidth: 1,
                                        strokeStyle: "#ff00ff",
                                        fillStyle: "#ffff00",
                                        setLineDash: [5, 15],
                                });

                                testRect.x = info.posx * _self.data.pixelRatio;
                                testRect.y = info.posy * _self.data.pixelRatio;
                                testRect.originX = 0;
                                testRect.originY = 0;
                                testRect.scaleX = info.scalex ? info.scalex : 1;
                                testRect.scaleY = info.scaley ? info.scaley : 1;
                                testRect.tag = info.tag;
                                gStage.add(testRect);
                                gStage.update();
                        }

                        let drawImage = function (info) {
                                let testImage = new cax.Bitmap(
                                        info.src,
                                        (e) => {
                                                console.log("load  image  ok")
                                                console.log(e)
                                                gStage.update();
                                        }
                                );

                                testImage.x = info.posx * _self.data.pixelRatio;
                                testImage.y = info.posy * _self.data.pixelRatio;
                                testImage.tag = info.tag;
                                testImage.scaleX = info.width / info.orignWidth;
                                testImage.scaleY = info.height / info.orignHeight;

                                testImage.tag = info.tag;
                                gStage.add(testImage);
                        }

                        let drawText = function (info) {
                                let testText = new cax.Text(info.src, {
                                        font: info.font,
                                        color: info.fontColor,
                                        baseline: 'top'
                                })

                                testText.x = info.posx * _self.data.pixelRatio;
                                testText.y = info.posy * _self.data.pixelRatio;
                                testText.tag = info.tag;
                                gStage.add(testText);
                                gStage.update();
                        }

                        for (let i = 0; i < testDrawData.length; i++) {
                                if (testDrawData[i].type == "rect") {
                                        drawRect(testDrawData[i]);
                                } else if (testDrawData[i].type == "image") {
                                        drawImage(testDrawData[i]);
                                } else if (testDrawData[i].type == "text") {
                                        drawText(testDrawData[i]);
                                }
                        }

                }, 1000);


        },

        onCopyToShowTarget() {
                this.copyToTarget(gTargetCtx);
        },

        onCopyToOffTarget() {
                // 创建离屏 2D canvas 实例
                if (gOffScreenCanvas == null) {
                        gOffScreenCanvas = jd.createOffscreenCanvas({
                                type: '2d',
                                width: this.data.canvasWidth,
                                height: this.data.canvasHeight
                        })
                        // 获取 context。注意这里必须要与创建时的 type 一致
                        gOffScreenCtx = gOffScreenCanvas.getContext('2d')

                }

                this.copyToTarget(gOffScreenCtx);
        },

        copyToTarget(inCtx) {
                console.log("copyToTarget --- start")
                console.log("copyToTarget --- after ctx")

                let drawRect = function (info) {
                        console.log("copyToTarget --- rect --- ")
                        inCtx.lineWidth = 1;
                        inCtx.fillStyle = "#ffff00";
                        inCtx.strokeStyle = "#ff00ff";
                        inCtx.rect(info.posx, info.posy, info.width, info.height);
                        inCtx.fill();
                        inCtx.stroke();
                }


                let drawImage = function (info) {
                        console.log("copyToTarget --- image --- ")
                        jd.getImageInfo({
                                src: info.src,
                                success(res) {
                                        console.log("copyToTarget --- image --- loaded")
                                        console.log(res)

                                        inCtx.drawImage(res.path, info.posx, info.posy, info.width, info.height);
                                        console.log(gTargetImageCount)
                                        gTargetImageCount--;
                                        if (gTargetImageCount == 0)
                                                inCtx.draw()
                                }
                        })
                }

                let drawText = function (info) {
                        inCtx.font = info.font;
                        inCtx.fillStyle = info.fontColor;
                        inCtx.textBaseline = "top";
                        // inCtx.textAlign = "center";
                        inCtx.fillText(info.src, info.posx, info.posy);
                }

                gTargetImageCount = 0;
                for (let j = 0; j < testDrawData.length; j++) {
                        if (testDrawData[j].type == "image")
                                gTargetImageCount++;
                }
                for (let i = 0; i < testDrawData.length; i++) {
                        console.log("copyToTarget --- i --- " + i)

                        if (testDrawData[i].type == "rect")
                                drawRect(testDrawData[i]);
                        else if (testDrawData[i].type == "image") {
                                drawImage(testDrawData[i]);
                        } else if (testDrawData[i].type == "text") {
                                drawText(testDrawData[i]);
                        }
                }
                if (gTargetImageCount == 0)
                        inCtx.draw()
        },

        genShotImage: function () {
                // 将生成的canvas图片，转为真实图片
                console.log("onGetShot() ----------------------");
                jd.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        canvasId: 'targetcanvas',
                        success: function (resp) {
                                console.log(resp)

                                jd.uploadFile({
                                        url: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/jd_starbucks/test_img",
                                        filePath: resp.tempFilePath,
                                        name: "file",
                                        FormData: {
                                                key: "LTAItxyGCMayI8ko",
                                                policy: '',
                                                OSSAccessKeyId: "UbrKH8OUiPOHrO7ZDRN2oZq5loI8Dv",
                                                signature: "",
                                                success_action_status: '200'
                                        },

                                        success: function (res) {
                                                if (res.statusCode != 200) {
                                                        console.log("上传失败")
                                                } else {
                                                        console.log("上传成功")
                                                }
                                        },
                                        fail: function (err) {
                                                console.log("上传 --- fail")
                                                console.log(err)
                                        }
                                })


                                // jd.saveImageToPhotosAlbum({
                                //         filePath: resp.tempFilePath,
                                //         success(res) {
                                //                 jd.showToast({
                                //                         title: '保存成功',
                                //                         icon: 'success',
                                //                         duration: 1500
                                //                 })
                                //         }
                                // })
                        },
                        fail: function (res) {}
                })
        },

        // onTouchStart(e) {
        //         console.log("onTouchStart() --- onTouchStart");
        // },

        // onTouchMove(e) {
        //         console.log("onTouchMove() --- onTouchMove");

        // },

        // onTouchEnd(e) {
        //         console.log("onTouchEnd() --- onTouchEnd");

        // },

        touchStart(e) {
                console.log(`onTouchStart() --- ${e.touches[0].x} -- ${e.touches[0].y} `);
                console.log(e);
        },

        touchMove(e) {
                console.log(`touchMove() --- ${e.touches[0].x} -- ${e.touches[0].y} `);
                console.log(e);
        },

        touchEnd(e) {
                console.log(`touchEnd() ---  `);
        },
});